package cqrtplm.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.service.TyplmObjectAliasService;
import com.hustcad.plm.pdm.audit.util.TyplmAuditLogUtil;
import com.hustcad.plm.pdm.ec.module.dto.ECAddChangeObjectDTO;
import com.hustcad.plm.pdm.ec.module.dto.ECObjDTO;
import com.hustcad.plm.pdm.ec.module.dto.ECObjData;
import com.hustcad.plm.pdm.ec.module.dto.EcAfterAddReturnDTO;
import com.hustcad.plm.pdm.ec.module.vo.ChgFormVO;
import com.hustcad.plm.pdm.ec.module.vo.EcAffectVO;
import com.hustcad.plm.pdm.ec.service.TyplmEngineeringChangeService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.mpmlink.service.TyplmMpmPartAdaptationService;
import com.hustcad.plm.pdm.mpmlink.service.part.TyplmMpmPartService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.TyPartAllVO;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.part.PartMasterDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.session.TyAccountContext;
import com.ty.security.util.TyCommonUtils;
import cqrtplm.constant.RouteConstant;
import cqrtplm.dto.OrderChangeDTO;
import cqrtplm.dto.RtCfgStatusDTO;
import cqrtplm.service.OrderChangeService;
import cqrtplm.service.impl.RtCfgStatusInfoServiceImpl;
import cqrtplm.vo.RtCfgStatusInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
@RequestMapping(RouteConstant.RTOAORDER + "/api/order-change")
public class OrderChangeController {

    @Autowired
    private OrderChangeService orderChangeService;
    @Resource
    private TyplmEngineeringChangeService typlmEngineeringChangeService;
    @Resource
    private TyplmPartService typlmPartService;
    @Resource
    private RtCfgStatusInfoServiceImpl typlmMpmPartService;
    @Resource
    private TyplmPdmPartService typlmPdmPartService;

    @PostMapping("/add")
    public ResponseResult create(@RequestBody OrderChangeDTO dto) throws Exception {

        try {
            orderChangeService.create(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("400", e.getMessage());
        }

        return ResponseResult.success();
    }

    @PutMapping
    public ResponseResult update(@RequestBody OrderChangeDTO dto) throws Exception {
        try {
            orderChangeService.update(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("400", e.getMessage());
        }

        return ResponseResult.success();
    }

    @GetMapping("/{oid}")
    public ResponseResult getByOid(@PathVariable String oid) {
        return ResponseResult.success(orderChangeService.getByOid(oid));
    }

    @DeleteMapping("/{oid}")
    public ResponseResult delete(@PathVariable String oid) throws Exception {

        try {
            if (oid == null || oid.trim().isEmpty()) {
                new IllegalStateException("OID 不能为空");
            }
            orderChangeService.delete(oid);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("400", e.getMessage());
        }
        return ResponseResult.success("删除成功");
    }

    @PostMapping("/createECN")
    public ResponseResult createECN(@RequestBody OrderChangeDTO dto) throws Exception {
        try {
            List<MultipartFile> fileList = new ArrayList<>();
            TyPartAllVO fatherPartDO = typlmPartService.queryPartAllVO(new BigInteger(dto.getHeader().getOid()),
                                                                       TableTypeConstrant.TY_PART_OTYPE);
            LinkedHashMap<String, String> descriptionMap = new LinkedHashMap<>();
            RtCfgStatusDTO rtCfgStatusDTO = new RtCfgStatusDTO();
            // 设置状态码
            //            rtCfgStatusDTO.setStatusCode(fatherPartDO.getMasterPartNumber());
            rtCfgStatusDTO.setOid(fatherPartDO.getOid().toString());
            // 调用服务获取结果
            com.hustcad.plm.pdm.file.handler.response.ResponseResult rtCfgStatusInfoByModuleIdOrStatusCode = typlmMpmPartService.getRtCfgStatusInfoByModuleIdOrStatusCode(
                    rtCfgStatusDTO);

            // 检查返回是否成功
            if (!"SUCCESS".equals(rtCfgStatusInfoByModuleIdOrStatusCode.getResult())) {
                throw new RuntimeException("获取配置状态失败: " + rtCfgStatusInfoByModuleIdOrStatusCode.getMessage());
            }

            // 获取 data 中的 rtCfgStatusInfo
            RtCfgStatusInfoVO data = (RtCfgStatusInfoVO) rtCfgStatusInfoByModuleIdOrStatusCode.getData();

            // 提取字段
            String zmchengbom = data.getRtCfgStatusInfo().getZmchengbom();
            String dmchengbom = data.getRtCfgStatusInfo().getDmchengbom();
            String cdchengbom = data.getRtCfgStatusInfo().getCdchengbom();
            ChgFormVO formVO = new ChgFormVO();
            formVO.setName(fatherPartDO.getName() + "变更单");
            formVO.setContainerOid(fatherPartDO.getContaineroid());
            formVO.setContainerOtype(fatherPartDO.getContainerotype());
            formVO.setTypeOid(new BigInteger("755406815458639872"));
            formVO.setTypeotype("ty.inteplm.type.CTyTypeDef");
            formVO.setCreatorName(TyAccountContext.getUser().getName());
            formVO.setOwnerName(TyAccountContext.getUser().getName());
            List<ECObjDTO> ecObjectList = new ArrayList<>();
            ECObjDTO ecObj = new ECObjDTO();
            ecObj.setOid(fatherPartDO.getOid());
            ecObj.setOtype(fatherPartDO.getOtype());
            ecObjectList.add(ecObj);
            formVO.setEcNumber("XQBG" + Instant.now().getEpochSecond());
            formVO.setEcObjectList(ecObjectList);
            List<ECObjData> ecAffectVOList = new ArrayList<>();
            formVO.setEcAffectVOS(ecAffectVOList);
            ChgFormVO chgForm = typlmEngineeringChangeService.createChgFormNew(formVO, fileList, descriptionMap);
            List<ECObjDTO> ecObjectList1 = new ArrayList<>();
            ECObjDTO ecObj1 = new ECObjDTO();
            if (!StringUtils.isBlank(zmchengbom)) {
                PartDO zmchengbomPart = typlmPdmPartService.queryLastPartDoByPartNumber(zmchengbom);
                ecObj1.setOid(zmchengbomPart.getOid());
                ecObj1.setOtype(zmchengbomPart.getOtype());
                ecObjectList1.add(ecObj1);
            }
            if (!StringUtils.isBlank(dmchengbom)) {
                PartDO dmchengbomPart = this.typlmPdmPartService.queryLastPartDoByPartNumber(dmchengbom);
                ecObj1.setOid(dmchengbomPart.getOid());
                ecObj1.setOtype(dmchengbomPart.getOtype());
                ecObjectList1.add(ecObj1);

            }
            if (!StringUtils.isBlank(cdchengbom)) {
                PartDO cdchengbomPart = this.typlmPdmPartService.queryLastPartDoByPartNumber(cdchengbom);
                ecObj1.setOid(cdchengbomPart.getOid());
                ecObj1.setOtype(cdchengbomPart.getOtype());
                ecObjectList1.add(ecObj1);
            }

            if (ecObjectList1.size() > 0) {
                ECAddChangeObjectDTO addChangeAfterObjectDTO = new ECAddChangeObjectDTO();
                addChangeAfterObjectDTO.setEntity(new IdentifierEntity(chgForm.getOid(), chgForm.getOtype()));
                addChangeAfterObjectDTO.setEntityList(ecObjectList1);
                addChangeAfterObjectDTO.setOirAllObjList(new ArrayList<>());
                addChangeAfterObjectDTO.setRootList(new ArrayList<>());
                this.typlmEngineeringChangeService.addAfterChangeObject(addChangeAfterObjectDTO);
            }

            TyplmAuditLogUtil.info(chgForm.getOid(), chgForm.getOtype(), LogEventEnum.CRATE_OBJECT);
            TyplmAuditLogUtil.sendCollectInfo();
            return ResponseResult.success(chgForm);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("400", e.getMessage());
        }

    }

}